import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
///基础消息通道
class BasicMessageChannelPage extends StatefulWidget {
  const BasicMessageChannelPage({super.key});

  @override
  State<BasicMessageChannelPage> createState() => _BasicMessageChannelPageState();
}

class _BasicMessageChannelPageState extends State<BasicMessageChannelPage>{
  String? _message;
  static const _channel = const BasicMessageChannel<String>(
    'messageChannel',
    StringCodec(),
  );

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _channel.setMessageHandler((message) async {
      print('message: $message');
      setState(() {
        _message = message;
      });
      return 'message from flutter>安卓';
    });
  }

  Future<void> _sendMessage() async{
    String? message = await _channel.send('message from flutter');
    print("Send message:$message");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Basic Message Channel'),
      ),
      body: Center(
        child: Text(_message ?? ''),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _sendMessage,
        child: const Icon(Icons.add),
      ),
    );
  }
}
